<template>
  <div class="login">

    <div class="login_show">
      <h1 class="login_font">注册</h1>
      <span @click="close_register" class="close_font">X</span>
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

        <el-form-item label="手机号" prop="pass">
          <el-input type="username" v-model="mobile" autocomplete="off" prefix-icon="el-icon-user" @blur="click_mobile"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="checkPass">
          <el-input type="password" v-model="password" autocomplete="off"
                    prefix-icon="el-icon-key"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="password">
          <el-input placeholder="验证码"
                    v-model="sms"
                    autocomplete="off"
                    prefix-icon="el-icon-chat-line-round">
            <template slot="append">
              <span class="sms" @click="send_sms">{{ sms_interval }}</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="register">注册</el-button>
<!--          <el-button @click="resetForm('ruleForm')">重置</el-button>-->
        </el-form-item>
      </el-form>
      <div class="foot">
        <span @click="go_login">立即登录</span>
      </div>
    </div>

  </div>
</template>

<script>
export default {
  name: "login",
  data() {
    // var checkAge = (rule, value, callback) => {
    //   if (!value) {
    //     return callback(new Error('年龄不能为空'));
    //   }
    //   setTimeout(() => {
    //     if (!Number.isInteger(value)) {
    //       callback(new Error('请输入数字值'));
    //     } else {
    //       if (value < 18) {
    //         callback(new Error('必须年满18岁'));
    //       } else {
    //         callback();
    //       }
    //     }
    //   }, 1000);
    // };
    // var validatePass = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('请输入密码'));
    //   } else {
    //     if (this.ruleForm.checkPass !== '') {
    //       this.$refs.ruleForm.validateField('checkPass');
    //     }
    //     callback();
    //   }
    // };
    // var validatePass2 = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('请再次输入密码'));
    //   } else if (value !== this.ruleForm.pass) {
    //     callback(new Error('两次输入密码不一致!'));
    //   } else {
    //     callback();
    //   }
    // };
    return {
      // ruleForm: {
      //   pass: '',
      //   checkPass: '',
      //   age: ''
      // },
      // rules: {
      //   pass: [
      //     {validator: validatePass, trigger: 'blur'}
      //   ],
      //   checkPass: [
      //     {validator: validatePass2, trigger: 'blur'}
      //   ],
      //   age: [
      //     {validator: checkAge, trigger: 'blur'}
      //   ]
      // },
      password: '',
      mobile: '',
      sms: '',
      login_control: 'is_pwd',
      sms_interval: '发送验证码',
      is_send: false,
    };
  },
  methods: {
    close_register() {
      this.$emit('close')
    },
    go_login() {
      this.$emit('go');
    },

    click_mobile() {
      if (!this.mobile) {
        return
      }
      if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
        this.$message({
          message: '手机号有误',
          type: 'warning',
          duration: 1000,
          onClose: () => {
            this.mobile = ''
          }
        })
        return false
      }
      // 发送axios请求
      this.$axios.get(this.$settings.base_url + '/user/check_telephone/', {params: {telephone: this.mobile}}).then(response => {
        if (response.data.code) {
          //手机号存在
          this.$message({
            message: '您已经注册过了，快去登录吧',
            type: 'warning',
            duration: 1000,
            onClose: () => {
              this.go_login()
            }
          })
        } else {
          this.is_send = true
          this.$message({
            message: '该用户没有注册过，欢迎注册我们的平台',
            type: 'success',
            duration: 1000,
          })
        }
      }).catch(error => {
        console.log(error)
      })

    },

    send_sms() {
      // 如果手机号合法，则可以点击获取验证码按钮，点击后设置一个1秒的定时器不断修改sms_interval，
      // 因为数据驱动页面，所以秒数会不停刷新
      if (!this.is_send) {
        return
      }
      this.is_send = false
      let sms_interval_time = 60;
      this.sms_interval = '发送中...'

      this.$axios.get(this.$settings.base_url + '/user/send/', {params: {'telephone': this.mobile}}).then(response => {
        console.log(this.mobile)
        // 因为后端没有短信服务，这里强行改成成功    this.response.code
        if (1) {
          this.$message({
            message: '发送验证码成功',
            type: 'success',
            duration: 1000,
          })
        }
      }).catch(error => {
      })

      let timer = setInterval(() => {
        if (sms_interval_time <= 1) {
          clearInterval(timer) // 如果小于等于1，把定时器清除
          this.sms_interval = '获取验证码'
          this.is_send = true // 重新恢复点击发送功能
        } else {
          sms_interval_time -= 1
          this.sms_interval = `${sms_interval_time}秒后再发`
        }
      }, 1000)

    },

    register() {
      if (this.mobile && this.sms && this.password) {
        this.$axios.post(this.$settings.base_url + '/user/register/', {
          mobile: this.mobile,
          code: this.sms,
          password: this.password
        }).then(response => {
          if (response.data.code) {
            //注册成功，来个提示，跳转到登录
            this.$message({
              message: '注册成功',
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.go_login()
              }
            })
          } else {
            this.$message({
              message: '未知错误',
              type: 'error',
              duration: 1000,
              onClose: () => {
                this.mobile=''
                this.sms=''
                this.password=''
              }
            })
          }

        }).catch(error => {
        })
      } else {
        this.$message({
              message: '你有未填写的信息',
              type: 'error',
              duration: 1000,
            })
      }
    },

    // submitForm(formName) {
    //   this.$refs[formName].validate((valid) => {
    //     if (valid) {
    //       alert('submit!');
    //     } else {
    //       console.log('error submit!!');
    //       return false;
    //     }
    //   });
    // },
    // resetForm(formName) {
    //   this.$refs[formName].resetFields();
    // }

  }
}
</script>

<style scoped>
.login {
  width: 100vw;
  height: 100vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 666;
  background-color: rgba(0, 0, 0, 0.3);
}

.close_font {
  font-size: 20px;
  cursor: pointer;
  position: fixed;
  margin-right: 0;
}

.login_font {
  font-size: 20px;
  padding-top: 10px;
  margin-top: 10px;
}

.login_show {
  background-color: #fafafa;
  width: 500px;
  height: 300px;
  margin-left: calc(50% - 500px / 2);
  margin-top: 100px
}

.demo-ruleForm {
  width: 400px;
  height: 200px;
  padding-top: 30px;
}
</style>
